package com.wiz.weixin.controllor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.service.PrPriceService;
import com.wiz.weixin.service.ScanRefuelingService;
import com.wiz.weixin.to.PrPriceTO;
import com.wiz.weixin.util.PastUtil;
import com.wiz.weixin.vo.AuthVO;
import com.wiz.weixin.vo.MemberVO;
import com.wiz.weixin.vo.ResultVO;

/**
 * 扫一扫加油
 * @author xxy
 */
@Controller
@RequestMapping("/scanRefueling")
public class ScanRefuelingControllor {
	private transient final Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private TencentManager tencentManager;
	@Resource
	private ScanRefuelingService scanRefuelingService;
	@Resource
	private MemberService memberService;
	@Resource
	private PrPriceService prPriceService;

	/** 扫一扫 */
	@RequestMapping(value = "/toAuthorization")
	public String toAuthorization(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "qrId", required = true) String qrId, HttpSession session, Model model)
					throws Exception{
		String code = request.getParameter("code");
		log.info("qrId="+qrId+" will be toAuthorization..... code="+code);
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/scanRefueling/checkin_fail";
		}
//		String openId = "ovNRGs45WudglvjfjUth3W57tJOU";
		String openId = tencentManager.getOpenId(code);
		if (StringUtils.isBlank(openId)) {
			model.addAttribute("msg", "无法取得微信用户编码");
			return "/scanRefueling/checkin_fail";
		}
		session.setAttribute("openid", openId);
		PrPriceTO prPriceTO = prPriceService.getPrPricebyQrId(qrId);
		if(prPriceTO==null){
			model.addAttribute("msg", "没有找到该油枪信息");
			return "/scanRefueling/checkin_fail";
		}
		MemberVO memberVO = memberService.getMemberByOpenId(openId, prPriceTO.getHqId());
		if(memberVO == null){
			model.addAttribute("msg", "没有找到当前油站对应的会员！");
			return "/scanRefueling/checkin_fail";
		}
		if(memberVO.getStatus() != 1){
			model.addAttribute("msg", "账户已冻结或已注销！");
			return "/scanRefueling/checkin_fail";
		}
		model.addAttribute("prPrice", prPriceTO);
		model.addAttribute("member", memberVO);
		log.info("member="+memberVO.getMemberId()+" will fuelling");
		return "/scanRefueling/refuel2";
	}

	/** 授权 */
	@RequestMapping(value = "/authority", method = RequestMethod.POST)
	public String authorization(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "fpId", required = true) String fpId,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "memberId", required = true) String memberId,
			@RequestParam(value = "memberName", required = true) String memberName,
			@RequestParam(value = "memberFrozenAmount", required = true) Double memberFrozenAmount,
			@RequestParam(value = "isCheckFuellingPw", required = true) Integer isCheckFuellingPw, HttpSession session,
			Model model) throws Exception {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PastUtil.setJsSdkInModel(model);
		AuthVO authVO = new AuthVO(fpId, stationId, memberId, memberName, memberFrozenAmount, 1);
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/scanRefueling/checkin_fail";
		}
		// 判断是否需要验证加油密码
		if (isCheckFuellingPw != null && isCheckFuellingPw == 1) {
			model.addAttribute("authVO", authVO);
			return "/scanRefueling/toPassword";
		}
		ResultVO result = scanRefuelingService.authorization(authVO);
		if(result.getCode() == 0){
			return "/scanRefueling/authorization";
		}else{
			model.addAttribute("msg", result.getMsg());
			return "/scanRefueling/checkin_fail";
		}
	}

	/** 验证密码、授权 */
	@RequestMapping(value = "/verifyAuth", method = RequestMethod.POST)
	public String verifyAuth(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "fpId", required = true) String fpId,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "memberId", required = true) String memberId,
			@RequestParam(value = "memberName", required = true) String memberName,
			@RequestParam(value = "memberFrozenAmount", required = true) Double memberFrozenAmount,
			@RequestParam(value = "password", required = true) String password, HttpSession session, Model model)
					throws Exception {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		AuthVO authVO = new AuthVO(fpId, stationId, memberId, memberName, memberFrozenAmount, 1);
		int check = memberService.checkMemberPassword(memberId, password);
		if (check < 1) {
			model.addAttribute("msg", "密码错误");
			return "/scanRefueling/checkin_fail";
		}
		ResultVO result = scanRefuelingService.authorization(authVO);
		if(result.getCode() == 0){
			return "/scanRefueling/authorization";
		}else{
			model.addAttribute("msg", result.getMsg());
			return "/scanRefueling/checkin_fail";
		}
	}

	/** 积分授权 */
	@RequestMapping(value = "/pointAuth")
	public String pointAuth(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "fpId", required = true) String fpId,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "memberId", required = true) String memberId,
			@RequestParam(value = "memberName", required = true) String memberName,
			HttpSession session, Model model) throws Exception {
		AuthVO authVO = new AuthVO(fpId, stationId, memberId, memberName, 0.0, 2);
		ResultVO result = scanRefuelingService.authorization(authVO);
		if(result.getCode() == 0){
			return "/scanRefueling/point_success";
		}else{
			model.addAttribute("msg", result.getMsg());
			return "/scanRefueling/checkin_fail";
		}
	}

}
